﻿package kliment.display.draw.shape {
	import flash.geom.Point;
	import kliment.display.draw.DrawStyle;
	import kliment.geom.Geom;
	import kliment.geom.PointExtended;
	import kliment.geom.Quadrangle;
	
	/**
	 * ...
	 * @author Kliment
	 */
	public class TrapeziumBy2PointsShape extends ShapeAbstract {
		
		public function TrapeziumBy2PointsShape(a:PointExtended, b:PointExtended, width:Number, drawStyle:DrawStyle = null) {
			super();
			
			a.angle = Geom.getNormalAngle(a.angle);
			b.angle = Geom.getNormalAngle(b.angle);
			
			var pointA:PointExtended = a.cloneme(); 
				pointA.angle = -pointA.angle;
			var pointB:PointExtended = b.cloneme();
			
			function getConer(k:Number, c:Number):Number{ return Math.asin(k/c); }
			
			var p1:Point = new Point();
			var p2:Point = new Point();
			var p3:Point = new Point();
			var p4:Point = new Point();
			
			var halfWidth:Number = width / 2;
			var height:Number = Point.distance(a, b);
			var helfHeight:Number = height / 2;
		
			var right:Point = Geom.rightPoint(a,b);
			var center:Point = Point.interpolate(a,b, .5);
			var rc:Point = new Point(right.x , center.y);
			
			var angle:Number = 0;
			
			var bt:Number = 0;
			var ct:Number = 0;
			
			if (right.y > center.y) {
				var bottom:Point = Geom.bottomPoint(a, b);
				bt = Point.distance(rc, bottom);
				ct = Point.distance(center, bottom);
				angle = getConer(bt, ct);
			} else if(right.y < center.y) {
				var top:Point = Geom.topPoint(a,b);
				bt = Point.distance(rc, top);
				ct = Point.distance(center, top);
				angle = -getConer(bt, ct);
			}
			
			if (right == a) {
				var tp:PointExtended = pointA;
				pointA = pointB;
				pointB = tp;
			}
			
			p1.x = center.x - helfHeight;
			p1.y = center.y - halfWidth;
			p2.x = center.x + helfHeight;
			p2.y = p1.y;
			p3.x = p2.x;
			p3.y = center.y + halfWidth;
			p4.x = p1.x;
			p4.y = p3.y;
			
			var addL:Number = Math.tan(Geom.gradToRad(pointA.angle)) * halfWidth;
			p4.x += addL;
			p1.x -= addL;
			
			if (p1.x > p2.x){
				p4.x += p1.x - p2.x;
				p1.x = p2.x;
			} else if (p3.x < p4.x){
				p1.x += p4.x - p3.x;
				p4.x = p3.x;
			}
			
			var addR:Number = Math.tan(Geom.gradToRad(pointB.angle)) * halfWidth;
			p2.x += addR;
			p3.x -= addR;

			if (p2.x < p1.x) {
				p3.x += p1.x - p2.x;
				p2.x = p1.x;
			} else if (p3.x < p4.x) {
				p2.x += p4.x - p3.x;
				p3.x = p4.x;
			}
			
			var qr:Quadrangle = new Quadrangle(p1, p2, p3, p4, center);
			qr.angle = Geom.radToGrad(angle);
			
			LinesShape.draw(graphics, new Point(), qr.toDrawArray(), drawStyle);
		}
		
	}
	
}